class CategoryController < ApplicationController
  before_filter :login_required
  layout "main"
  scaffold :category
  
  def index
    list
    render :action=> "list"
  end
  
  def list
    @current = "categories"
    @page_title = "All Categories"
    user = User.find_by_id(session[:user].id)
    
    @category_pages, @categories = paginate_collection user.categories.find(:all,:order => "title"), 
                                                                          :page => params[:page], :per_page => 50
  end
  
  def new
    @current = "category"
    @page_title = "Create new Category"
    user = User.find_by_id(session[:user].id)
    
    @category = user.categories.new(params[:category])
    @category.user_id = user.id
    if request.post? and @category.save
      flash[:notice] ="Category '#{@category.title}' was added"
      @category = Category.new
      redirect_to :controller => 'category'
    end 
  end
  
  def edit
    @page_title = "Edit Category"
    @current = "category"
    @page_title = "Create new Category"
    user = User.find_by_id(session[:user].id)
    @category = user.categories.find(params[:id])
    
    if request.post? 
      @category.update_attributes(params[:category])
      if @category.update
        flash[:notice] ="Category '#{@category.title}' updated"
        redirect_to :controller => 'category'
      end
    end      
  end
  
  def delete
  
    user = User.find_by_id(session[:user].id)
    category = user.categories.find(params[:id])
    
    # Delete the user's category
    user.categories.delete(category)
    
    # Clear out any existing category <-> story
    # relationships.
    user.stories.each do |story|
      story.categories.delete(category)
    end
    
    flash[:notice] = "Category \"#{category.title}\" deleted"
    redirect_to :controller => 'category'
    
  end
end
